package com.ityuwen.mengyagushi.user.listener;

import com.alibaba.fastjson.JSON;
import com.ityuwen.mengyagushi.album.client.TrackInfoFeignClient;
import com.ityuwen.mengyagushi.common.constant.KafkaConstant;
import com.ityuwen.mengyagushi.common.constant.SystemConstant;
import com.ityuwen.mengyagushi.common.result.Result;
import com.ityuwen.mengyagushi.model.album.TrackInfo;
import com.ityuwen.mengyagushi.model.user.*;
import com.ityuwen.mengyagushi.user.mapper.*;
import com.ityuwen.mengyagushi.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Component
public class UserListener {

    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;

    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;

    @KafkaListener(topics = KafkaConstant.QUEUE_USER_PAY_RECORD)
    public void payRecord(String json){
        // 消息为空则直接结束
        if (StringUtils.isBlank(json)){
            return;
        }

        // 消息为空则直接结束
        UserPaidRecordVo userPaidRecordVo = JSON.parseObject(json, UserPaidRecordVo.class);
        if (userPaidRecordVo == null){
            return;
        }

        // 订单类型不同，记录不同的表
        String orderNo = userPaidRecordVo.getOrderNo();
        Long userId = userPaidRecordVo.getUserId();
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();
        if (CollectionUtils.isEmpty(itemIdList) || StringUtils.isBlank(orderNo) || userId == null){
            return;
        }
        switch (userPaidRecordVo.getItemType()){ // 专辑订单
            case SystemConstant.ORDER_ITEM_TYPE_ALBUM:
                // 判断是否已记录
                UserPaidAlbum userPaidAlbum = this.userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>()
                        .eq(UserPaidAlbum::getOrderNo, orderNo));
                if (userPaidAlbum != null){
                    return;
                }
                userPaidAlbum = new UserPaidAlbum();
                userPaidAlbum.setOrderNo(orderNo);
                userPaidAlbum.setUserId(userId);
                userPaidAlbum.setAlbumId(itemIdList.get(0));
                this.userPaidAlbumMapper.insert(userPaidAlbum);
                break;
            case SystemConstant.ORDER_ITEM_TYPE_TRACK: // 声音订单
                List<UserPaidTrack> userPaidTracks = this.userPaidTrackMapper.selectList(new LambdaQueryWrapper<UserPaidTrack>()
                        .eq(UserPaidTrack::getOrderNo, orderNo));
                if (!CollectionUtils.isEmpty(userPaidTracks)){
                    return;
                }
                // 根据声音id查询声音
                Result<TrackInfo> trackInfoResult = this.trackInfoFeignClient.getTrackInfo(itemIdList.get(0));
                Assert.notNull(trackInfoResult, "声音购买记录：获取声音信息失败！");
                TrackInfo trackInfo = trackInfoResult.getData();
                Assert.notNull(trackInfo, "声音购买记录：获取声音信息失败！");
                // 遍历itemIds集合转化成声音购买记录保存到声音购买记录表
                itemIdList.forEach(trackId -> {
                    UserPaidTrack userPaidTrack = new UserPaidTrack();
                    userPaidTrack.setOrderNo(orderNo);
                    userPaidTrack.setUserId(userId);
                    userPaidTrack.setTrackId(trackId);
                    userPaidTrack.setAlbumId(trackInfo.getAlbumId());
                    this.userPaidTrackMapper.insert(userPaidTrack);
                });
                break;
            case SystemConstant.ORDER_ITEM_TYPE_VIP:
                // 判断是否已记录过
                UserVipService userVipService = this.userVipServiceMapper.selectOne(new LambdaQueryWrapper<UserVipService>()
                        .eq(UserVipService::getOrderNo, orderNo));
                if (userVipService != null){
                    return;
                }
                // 根据套餐id查询vip套餐
                VipServiceConfig vipServiceConfig = this.vipServiceConfigMapper.selectById(itemIdList.get(0));
                if (vipServiceConfig == null){
                    return;
                }

                // 组装vip购买记录
                userVipService = new UserVipService();
                userVipService.setOrderNo(orderNo);
                userVipService.setUserId(userId);
                // 查询用户是否已是vip
                UserInfo userInfo = this.userInfoMapper.selectById(userId);
                if (userInfo == null) {
                    return;
                }
                // 如果不是vip
                Date startTime = new Date();
                Date expireTime = LocalDateTime.fromDateFields(startTime).plusMonths(vipServiceConfig.getServiceMonth()).toDate();
                if (userInfo.getIsVip() == 1 && userInfo.getVipExpireTime().after(new Date())){
                    LocalDateTime startDataTime = LocalDateTime.fromDateFields(userInfo.getVipExpireTime()).plusDays(1);
                    startTime = startDataTime.toDate();
                    expireTime = startDataTime.plusMonths(vipServiceConfig.getServiceMonth()).toDate();
                }
                userVipService.setStartTime(startTime);
                userVipService.setExpireTime(expireTime);
                userInfo.setIsVip(1);
                userInfo.setVipExpireTime(expireTime);

                this.userVipServiceMapper.insert(userVipService);
                this.userInfoMapper.updateById(userInfo);

                break;
        }
    }
}
